package com.hugong.cx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hugong.cx.entity.SysMenu;
import com.hugong.cx.mapper.SysMenuMapper;
import com.hugong.cx.service.ISysMenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cx
 * @since 2024-09-05
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {


    private final SysMenuMapper sysMenuMapper;

    public SysMenuServiceImpl(SysMenuMapper sysMenuMapper) {
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    public List<SysMenu> getByMenuAll(int hospitalManagementSystem) {
        //查询全部菜单,如果pid为0，则查询顶级菜单；否则查询指定pid下的子菜单
        List<SysMenu> sysMenuList = findSysMenuList(hospitalManagementSystem);
        System.out.println("sysMenuList = " + sysMenuList);
        return sysMenuList;
    }

    public List<SysMenu> findSysMenuList(Integer pid) {
//        查询全部菜单,如果pid为0，则查询顶级菜单；否则查询指定pid下的子菜单
        List<SysMenu> parentSysMenus = this.list(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getPid, pid));
        List<SysMenu> sysMenus = new ArrayList<>();

        // 递归构建评论树
        parentSysMenus.forEach(parentSysMenu -> {
            buildChildren(parentSysMenu);
            sysMenus.add(parentSysMenu);
        });
        return sysMenus;
    }

    //    查询子菜单
    private void buildChildren(SysMenu parentSysMenu) {
        List<SysMenu> children = this.list(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getPid, parentSysMenu.getId()));

        children.forEach(child -> {
            parentSysMenu.addChild(child);
            buildChildren(child); // 递归调用以构建更深层次的子评论
        });
    }


}
